package org.nmgyjt.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.beans.dto.BusAuthUserAddDto;
import org.nmgyjt.springboot.beans.dto.CyBusAuthUserAddDto;
import org.nmgyjt.springboot.beans.dto.CyBusAuthUserCodeDto;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.area.Area;
import org.nmgyjt.springboot.entity.exception.BizException;
import org.nmgyjt.springboot.entity.sms.YuFuMSSendEntity;
import org.nmgyjt.springboot.mapper.CsSystemAdminMapper;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.IDAASUserUtils;
import org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils;
import org.nmgyjt.springboot.utils.upload.SnowflakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-06-29
 */
@Service
@Slf4j
public class CsSystemAdminServiceImpl extends ServiceImpl<CsSystemAdminMapper, CsSystemAdmin> implements ICsSystemAdminService {


    @Autowired
    CsSystemMenuOrgInstitutionTemplateServiceImpl templateService;

    @Autowired
    ICsSystemAdminMenuRelService adminMenuRelService;

    @Autowired
    IAreaService areaService;

    @Autowired
    ICsSystemUserService userService;

    @Autowired
    ICsSystemSourcePreSetInfoService preSetInfoService;

    @Autowired
    ICsSystemDeptService deptService;

    @Autowired
    ICsSystemAdminMenuRelService menuRelService;

    @Autowired
    IIdaasAreaService idaasAreaService;

    @Autowired
    ICsSystemSourceTypeService sourceService;
    @Autowired
    ICsSystemSourceExtService csSystemSourceExtService;

    @Autowired
    SendSMSServiceImpl smsService;

    @Autowired
    IdaasService idaasService;


    @Autowired
    private ICsBusinessService csBusinessService;

    @Autowired
    private ICsBusinessUserService csBusinessUserService;

//    @Autowired
//    private ICsBusinessUserCodeService csBusinessUserCodeService;

    @Autowired
    private ICsBusinessAuthCodeService csBusinessAuthCodeService;

    @Autowired
    private IBusinessAuthService businessAuthService;

    @Override
    public String createCsSystemAdmin(CsSystemAdminCreateBean bean, UserInfo loginAdminInfo) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        CsSystemAdmin systemAdmin = null;
        LambdaQueryWrapper<CsSystemAdmin> queryWrapper = new LambdaQueryWrapper<CsSystemAdmin>()
                .eq(CsSystemAdmin::getPhone, bean.getCreatedBy())
                .like(CsSystemAdmin::getMenuPermission, bean.getMenuID());
        if (StringUtils.isNotEmpty(bean.getOrgId())) {
            queryWrapper.eq(CsSystemAdmin::getOrgId, bean.getOrgId());
        }

        if (!"1000000003".equals(bean.getMenuID()) && !"1000000005".equals(bean.getMenuID()) && !"1000000004".equals(bean.getMenuID())) {
            queryWrapper.eq(CsSystemAdmin::getAreaCode, bean.getAreaCode());
        }


        List<CsSystemAdmin> systemAdmins = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(systemAdmins) && systemAdmins.size() == 1) {
            systemAdmin = systemAdmins.get(0);
            if ("1000000007".equals(bean.getMenuID())) {
                //内设机构要校验内设机构的添加人数是否满足单位设置的最大人数
                String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + systemAdmin.getOrgId();
                HashMap<String, String> bodyParams = new HashMap<>();
                bodyParams.put("object_type", "DEPT");
                String clientPostRes = HttpUtils.httpGet(url, bodyParams, headerParams);
                IDAASDeptResponse loginUserOrg = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);

                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);

                IDAASDeptResponse innerDeptResponse = getOrgInfoFromIDAASOrgList(str2, "内设机构");
                String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + innerDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                List<IDAASDeptResponse> listResponse =
                        JSONArray.parseArray(str3, IDAASDeptResponse.class);
                int childrenOrgMaxUserNum = 0;
                if (!CollectionUtils.isEmpty(listResponse)) {
                    for (IDAASDeptResponse org : listResponse) {
                        childrenOrgMaxUserNum = childrenOrgMaxUserNum + org.getValues().getMaxUserNumber();
                    }
                    if (bean.getMaxUserNumber()> loginUserOrg.getValues().getMaxUserNumber()-childrenOrgMaxUserNum) {
                       return "单位可添加总人数为:" + loginUserOrg.getValues().getMaxUserNumber() + ";预设总数为:" + childrenOrgMaxUserNum
                                + ";新增内设机构最大可设置人数为:" + (loginUserOrg.getValues().getMaxUserNumber() - childrenOrgMaxUserNum);
                    }
                }

            }
        } else if (!CollectionUtils.isEmpty(systemAdmins) && systemAdmins.size() > 1) {
            HashMap<String, String> bodyParams = new HashMap<>();
            bodyParams.put("object_type", "DEPT");

            for (CsSystemAdmin ad : systemAdmins) {
                String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + ad.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url, bodyParams, headerParams);
                if (str1.contains(bean.getOrgName())) {
                    systemAdmin = ad;
                }
            }
        }

        if (null == systemAdmin) {
            return null;
        }

        CsSystemAdminMenuRel menuRel = menuRelService.getById(bean.getMenuID());
        if ("1000000017".equals(bean.getMenuID())) {
            bean.setMenuName("工委管理员");
        } else if (null != menuRel) {
            bean.setMenuName(menuRel.getName());
        }
        if (StringUtils.isEmpty(bean.getAreaCode())) {
            bean.setAreaCode(systemAdmin.getAreaCode());
        }
        if ("1000000001".equals(bean.getMenuID()) || "1000000001".equals(bean.getMenuID())) {

            String filterOrgName = null;
            Area area = areaService.getById(StringUtils.rightPad(loginAdminInfo.getValues().getRegionCode(), 12, "0"));
            if ("Province".equals(area.getRemark())) {

                filterOrgName = "1000000001".equals(bean.getMenuID()) ? "自治区党委" : "自治区政府";

            } else if ("City".equals(area.getRemark())) {

                filterOrgName = "1000000001".equals(bean.getMenuID()) ? "盟市党委（盟委）" : "盟市政府（行署）";

            } else if ("County".equals(area.getRemark())) {

                filterOrgName = "1000000001".equals(bean.getMenuID()) ? "旗县党委" : "旗县政府";

            }
            bean.setOrgName(filterOrgName);
        } else if ("1000000007".equals(bean.getMenuID())) {
            bean.setOrgName(systemAdmin.getOrgName());
            bean.setWorkUnit(systemAdmin.getOrgName());
        }

        //返回来的部门解析获取最终能完全匹配的部门信息;
        IDAASDeptResponse deptResponse = null;


        CsSystemOrgCreateBean orgCreateBean = new CsSystemOrgCreateBean();
        BeanUtils.copyProperties(bean, orgCreateBean);
        //orgCreateBeanxadmin.getId());
        orgCreateBean.setAdminOrgID(systemAdmin.getOrgId());
        orgCreateBean.setAreaCode(loginAdminInfo.getValues().getRegionCode());
        orgCreateBean.setMaxUserNumber(bean.getMaxUserNumber());
        if (!CollectionUtils.isEmpty(bean.getPreSetOrgInfos()) && JSONObject.toJSONString(bean.getPreSetOrgInfos()).contains("1000000007"))
            orgCreateBean.setPreSetOrgInfos(bean.getPreSetOrgInfos());
        if (!StringUtils.isEmpty(bean.getPageType())) {
            orgCreateBean.setPageType(bean.getPageType());
        }
        orgCreateBean.setCreatedBy(bean.getCreatedBy());
        IDAASOrgEntity csSystemOrg = deptService.createCsSystemOrg(orgCreateBean);
    /*    if (null !=csSystemOrg && StringUtils.isEmpty(csSystemOrg.getId()) && null != deptResponse) {
            csSystemOrg.setId(deptResponse.getId());
        }
        if (StringUtils.isEmpty(csSystemOrg.getParentId()) && null != deptResponse) {
            csSystemOrg.setParentId(deptResponse.getValues().getParentId());
        }*/


        //1.根据管理员的手机号码查询用户信息,如果存在就返回,不存在就先创建人员信息在返回;
        if (null == csSystemOrg) {
            throw new BizException("创建管理员失败,管理员所在机构管理员节点获取失败!");
        }
        UserInfo userInfo = null;
        userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getPhone());
        /**
         * 查询用户,如果不存在就添加用户
         */
        boolean flag = false;
        if (null == userInfo) {
            if (null != csSystemOrg) {
                userInfo = createUserToIDAAS(bean, csSystemOrg.getId(), csSystemOrg.getRegionCode());
                flag = true;
            } else {
                return null;
            }
        } else {

            /**
             *  如果用户存在如果用户存在,则直接把用户信息更新;
             */
            if (null != userInfo && "INACTIVE".equals(userInfo.getValues().getStatus())) {
                headerParams.put("Content-Type", "application/json");
                headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

                String userPostRes2 = HttpUtils.sendHttpPost("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/" + userInfo.getId() + "/enable", new JSONObject(), headerParams);
            }


            IDAASUserEntity po = new IDAASUserEntity();
            po.setWorkUnit(bean.getWorkUnit());
            po.setJobPosition(bean.getJob());
            po.setJobLevel(bean.getJobLevel());
            po.setDisplayName(bean.getName());
            po.setId(userInfo.getId());

            Map<String, String> bodyParams = new HashMap<>();
            bodyParams.put("object_type", "DEPT");

            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + userInfo.getValues().getDeptId();
            String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
            IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str2, IDAASDeptResponse.class);
            if (null != idaasDeptResponse && ("管理员".equals(idaasDeptResponse.getValues().getName()) || "dpf-3f90f739227e498bb3505237e6c397bb".equals(idaasDeptResponse.getId()))) {
                po.setDeptId(csSystemOrg.getId());
            }
            Map userMap = new HashMap<>();
            userMap.put("values", po);
            String userPostRes = HttpUtils.sendHttpPut("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/users/" + userInfo.getId(),
                    (JSONObject) JSON.toJSON(userMap), headerParams);
            log.info(userPostRes);

        }

        //2.查询相关机构信息,并获取相关机构的权限信息,组装实体对象
        //获取单位下的内设机构名单列表;
        Area area = areaService.getById(StringUtils.rightPad(bean.getAreaCode(), 12, "0"));
        String permission = ",";
        if ("1000000006".equals(bean.getMenuID())) {
            if (null != area) {

                CsSystemMenuOrgInstitutionTemplate template = templateService.getOne(new LambdaQueryWrapper<CsSystemMenuOrgInstitutionTemplate>()
                        .eq(CsSystemMenuOrgInstitutionTemplate::getOrgName, bean.getOrgName())
                        .eq(CsSystemMenuOrgInstitutionTemplate::getAreaLevel, area.getRemark()));
                if (!ObjectUtils.isEmpty(template) && CollectionUtils.isEmpty(bean.getPreSetOrgInfos())) {
                    if (1 == template.getMenuLead()) {
                        permission = permission + ",1000000009";
                    }
                    if (1 == template.getMenuOffice()) {
                        permission = permission + ",1000000007";
                    }
                    if (1 == template.getMenuInstitution()) {
                        permission = permission + ",1000000008";
                    }
                    if (1 == template.getMenuTeam()) {
                        permission = permission + ",1000000010";
                    }
                    if (1 == template.getMenuWarehouse()) {
                        permission = permission + ",1000000012";
                    }
                    if (1 == template.getMenuSupply()) {
                        permission = permission + ",1000000011";
                    }
                    if (1 == template.getMenuExpert()) {
                        permission = permission + ",1000000013";
                    }
                    if (1 == template.getMenuShelter()) {
                        permission = permission + ",1000000014";
                    }
                } else if (!CollectionUtils.isEmpty(bean.getPreSetOrgInfos())) {
                    //预设成员单位权限
                    for (CsSystemOrgPreSetBean preSetBean : bean.getPreSetOrgInfos()) {
                        permission = permission + "," + preSetBean.getId();
                        if ("1000000012".equals(preSetBean.getId()) && !CollectionUtils.isEmpty(preSetBean.getChildren())) {
                            //存入预设防护目标类型
                            CsSystemSourcePreSetInfo preSetInfo = new CsSystemSourcePreSetInfo();
                            preSetInfo.setId(SnowflakeIdWorker.getUUID());
                            preSetInfo.setOrgId(csSystemOrg.getParentId());
                            preSetInfo.setSourceId(preSetBean.getId());
                            preSetInfo.setPreSetTypes(JSONObject.toJSONString(preSetBean.getChildren()));
                            preSetInfo.setCreatedBy(bean.getCreatedBy());
                            preSetInfo.setUpdatedBy(bean.getCreatedBy());
                            preSetInfo.setCreatedTime(new Date());
                            preSetInfo.setUpdatedTime(new Date());
                            preSetInfoService.save(preSetInfo);
                        }

                        if ("1000000014".equals(preSetBean.getId()) && !CollectionUtils.isEmpty(preSetBean.getChildren())) {
                            //存入预设防护目标类型
                            CsSystemSourcePreSetInfo preSetInfo = new CsSystemSourcePreSetInfo();
                            preSetInfo.setId(SnowflakeIdWorker.getUUID());
                            preSetInfo.setOrgId(csSystemOrg.getParentId());
                            preSetInfo.setSourceId(preSetBean.getId());
                            preSetInfo.setPreSetTypes(JSONObject.toJSONString(preSetBean.getChildren()));
                            preSetInfo.setCreatedBy(bean.getCreatedBy());
                            preSetInfo.setUpdatedBy(bean.getCreatedBy());
                            preSetInfo.setCreatedTime(new Date());
                            preSetInfo.setUpdatedTime(new Date());
                            preSetInfoService.save(preSetInfo);
                        }

                        if ("1000002024".equals(preSetBean.getId())  && !CollectionUtils.isEmpty(preSetBean.getChildren()) ){
                            log.info("1000002024-new");
                            List<List<String>> listList1= preSetBean.getChildren();

                            CyBusAuthUserCodeDto cyBusAuthUserCodeDto = new CyBusAuthUserCodeDto();

                            List<CsBusinessUser> csBusinessUserList = new ArrayList<>();
//                            List<CsBusinessUserCode> userCodeList = new ArrayList<>();
                            List<CyBusAuthUserCodeDto> authUserDtos = new ArrayList<>();

                            for (List<String> l :  listList1){
                                CsBusinessUser csBusinessUser = new CsBusinessUser();

                                CsBusiness bu = csBusinessService.findByBusinessId(l.get(1));
                                csBusinessUser.setBusinessId(l.get(1));
                                csBusinessUser.setBusinessName(bu.getName());

                                CsBusiness pBu = csBusinessService.findByBusinessId(l.get(0));
                                csBusinessUser.setParentBusinessId(l.get(0));
                                csBusinessUser.setParentBusinessName(pBu.getName());

                                csBusinessUser.setPhone(bean.getPhone());
                                csBusinessUser.setCreatedTime(new Date());
                                csBusinessUser.setCreatedBy(bean.getCreatedBy());
                                csBusinessUserList.add(csBusinessUser);
                                List<CsBusinessAuthCode>  authCodeList = csBusinessAuthCodeService.list(new LambdaQueryWrapper<CsBusinessAuthCode>()
                                        .eq(CsBusinessAuthCode::getBusinessId, l.get(1))
                                        .eq(CsBusinessAuthCode::getParentBusinessId, l.get(0)));
                                if (CollUtil.isNotEmpty(authCodeList) ){
                                    for (CsBusinessAuthCode authCode : authCodeList ){
                                        if ("管理员".equals(authCode.getAuthName())){
                                            cyBusAuthUserCodeDto.setAuthCode(authCode.getAuthCode());
                                            cyBusAuthUserCodeDto.setAuthName(authCode.getAuthName());
                                            authUserDtos.add(cyBusAuthUserCodeDto);
                                        }
                                    }

                                }
//                                for (CsBusinessAuthCode authCode : authCodeList){
//                                    CsBusinessUserCode userCode = new CsBusinessUserCode();
//                                    userCode.setAuthCode(authCode.getAuthCode());
//                                    userCode.setPhone(bean.getPhone());
//                                    userCode.setCreatedTime(new Date());
//                                    userCode.setBusinessId(l.get(1));
//                                    userCode.setAuthName(authCode.getAuthName());
//                                    userCodeList.add(userCode);
//                                }

                            }
                            csBusinessUserService.saveBatch(csBusinessUserList);
//                            csBusinessUserCodeService.saveBatch(userCodeList);

                            CyBusAuthUserAddDto cyBusAuthUserAddDto = new CyBusAuthUserAddDto();
                            cyBusAuthUserAddDto.setPhone(bean.getPhone());
                            cyBusAuthUserAddDto.setUserName(bean.getName());
                            cyBusAuthUserAddDto.setAuthPhone(bean.getCreatedBy());
                            cyBusAuthUserAddDto.setAuthUserName(bean.getCreatedByName());
                            cyBusAuthUserAddDto.setAreaCode(bean.getAreaCode());
                            cyBusAuthUserAddDto.setAreaName(bean.getAreaName());
                            cyBusAuthUserAddDto.setDeptId(bean.getOrgId() );
                            cyBusAuthUserAddDto.setDeptName(bean.getOrgName());
                            cyBusAuthUserAddDto.setIp(bean.getIp());
                            cyBusAuthUserAddDto.setAuthUserDtos(authUserDtos);
                            //成员单位授权
                            businessAuthService.cydwsq(cyBusAuthUserAddDto);

                        }
                    }

                }
                permission = permission + "::";
                if (permission.contains(",,")) {
                    permission = permission.replace(",,", "");
                }
                /**
                 * 部门模板数据不为空,则拼装相关的部门权限信息;
                 */
            }
        }

        String[] menus = {"1000000001", "1000000002", "1000000003", "1000000004", "1000000005", "1000000006", "1000000008", "1000000011", "1000000012", "1000000013", "1000000014"};
        List<String> menuList = Arrays.asList(menus);

        CsSystemAdmin csSystemAdminEntity = new CsSystemAdmin();
        BeanUtils.copyProperties(bean, csSystemAdminEntity);
        csSystemAdminEntity.setStatus(1);
        csSystemAdminEntity.setCreatedBy(loginAdminInfo.getValues().getUsername());
        csSystemAdminEntity.setCreatedTime(new Date());
        csSystemAdminEntity.setUpdatedBy(loginAdminInfo.getValues().getUsername());
        csSystemAdminEntity.setUpdatedTime(new Date());
        csSystemAdminEntity.setAreaCode(area.getId());
        csSystemAdminEntity.setMenuPermission(",".equals(permission) ? setMenuPermission(bean.getMenuID()) : permission);
        if (("1000000003".equals(bean.getMenuID()) || "1000000004".equals(bean.getMenuID())) && bean.getOrgName().contains("开发区")) {
            String replacePermission = csSystemAdminEntity.getMenuPermission().replace("1000000001,1000000002", "1000000017");
            //2023-09-11:解决旗县管理员属于开发区没有乡镇指挥体系的问题
            replacePermission = replacePermission.replace("1000000005,", "");
            csSystemAdminEntity.setMenuPermission(replacePermission);
        }
        csSystemAdminEntity.setMenuId(bean.getMenuID());
        csSystemAdminEntity.setMenuName(bean.getMenuName());

        csSystemAdminEntity.setAreaName(area.getName());
        csSystemAdminEntity.setCsAdminLevel(area.getRemark());
        csSystemAdminEntity.setSuperiorOrg(systemAdmin.getOrgId());
        if ("1000000017".equals(bean.getMenuID())) {
            csSystemAdminEntity.setAdminType(17);
        } else {
            csSystemAdminEntity.setAdminType(
                    adminMenuRelService.getOne(new LambdaQueryWrapper<CsSystemAdminMenuRel>()
                            .eq(CsSystemAdminMenuRel::getId, bean.getMenuID())).getBeyongAdminType());
        }
        csSystemAdminEntity.setId(SnowflakeIdWorker.getUUID());
        csSystemAdminEntity.setWorkUnit(bean.getWorkUnit());
        if (menuList.contains(bean.getId())) {

            String[] resourceMenus = {"1000000010", "1000000011", "1000000012", "1000000014", "1000000013"};
            List<String> resourceMenuList = Arrays.asList(resourceMenus);
            if (resourceMenuList.contains(menuRel.getId())) {
                if ("2".equals(bean.getPageType())) {
                    csSystemAdminEntity.setOrgId(csSystemOrg.getId());
                } else {
                    csSystemAdminEntity.setOrgId(csSystemOrg.getParentId());
                }
            } else {
                csSystemAdminEntity.setOrgId(csSystemOrg.getParentId());
            }
            //资源类型的部门要额外存储或者更新资源类型等数据
            CsSystemSourceExt sourceExt = new CsSystemSourceExt();
            sourceExt.setSourceType(bean.getSourceType());
            sourceExt.setRemark(bean.getDesc());
            sourceExt.setSourceLevel(JSON.toJSONString(bean.getSourceLevel()));
            sourceExt.setMenuId(bean.getMenuID());
            if ("1000000013".equals(bean.getMenuID())) {
                sourceExt.setOrgId(userInfo.getId());
            } else {
                sourceExt.setOrgId(csSystemAdminEntity.getOrgId());
            }
            if ("1000000010".equals(bean.getMenuID())) {
                if (StringUtils.isNotEmpty(bean.getMajorDuties()))
                    sourceExt.setMajorDuties(bean.getMajorDuties());
                if (StringUtils.isNotEmpty(bean.getSecondaryDuties()))
                    sourceExt.setSecondaryDuties(bean.getSecondaryDuties());
            }
            CsSystemSourceExt one = csSystemSourceExtService.getOne(new LambdaQueryWrapper<CsSystemSourceExt>().eq(CsSystemSourceExt::getMenuId, bean.getMenuID()).eq(CsSystemSourceExt::getOrgId, sourceExt.getOrgId()).orderByDesc(CsSystemSourceExt::getId).last("limit 1"));
            if (resourceMenuList.contains(bean.getMenuID())) {
                if (null != one)
                    sourceExt.setId(one.getId());
                csSystemSourceExtService.saveOrUpdate(sourceExt);
                //详情更新
                idaasService.updateBaseSource(sourceExt, bean);
            }
        } else {
            if ("管理员".equals(csSystemOrg.getName()) || "1000000005".equals(menuRel.getId())) {
                csSystemAdminEntity.setOrgId(csSystemOrg.getParentId());
            } else {
                csSystemAdminEntity.setOrgId(csSystemOrg.getId());
            }
        }

      /*  List<CsSystemAdmin> admins = this.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, csSystemAdminEntity.getPhone()));
        if (!CollectionUtils.isEmpty(admins)) {
            for (CsSystemAdmin ad : admins) {
                this.removeById(ad.getId());
            }
        }*/

        CsSystemAdmin admin = this.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getOrgId, csSystemAdminEntity.getOrgId()).orderBy(true, false, CsSystemAdmin::getUpdatedBy).last("limit 1"));
        if (null != admin && !ObjectUtils.isEmpty(admin)) {
            csSystemAdminEntity.setId(admin.getId());
        }
        if (StringUtils.isEmpty(csSystemAdminEntity.getOrgId())) {
            csSystemAdminEntity.setOrgId(admin.getOrgId());
        }

        this.saveOrUpdate(csSystemAdminEntity);

        //发送通知短信
        //内蒙古应急信息维护系统】您好,{1},{2}管理员将您设置为{3}的{4}管理员。相关信息维护,请登录信息维护系统或联系相关责任人!

        if (flag) {
            HashMap<String, String> headerParams2 = new HashMap<>();
            headerParams2.put("Content-Type", "application/json");
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/" + userInfo.getId() + "/reset_password";

            Map restBean = new HashMap<>();
            restBean.put("password", "nmgYjt@" + userInfo.getValues().getUsername().substring(7, 11));
            restBean.put("scriptContent", "");
            restBean.put("script", false);
            String resetStr = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(restBean), headerParams);
        }


        if (null != userInfo && StringUtils.isNotEmpty(userInfo.getValues().getUsername())) {
            UserInfo idaasByOpenId = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(csSystemAdminEntity.getCreatedBy());
            YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
            List<String> params = new ArrayList<>();
            List<String> phone = new ArrayList<>();
            phone.add(userInfo.getValues().getUsername());
            params.add(userInfo.getValues().getDisplayName());
            if (null != idaasByOpenId && !ObjectUtils.isEmpty(idaasByOpenId.getValues())) {
                params.add(idaasByOpenId.getValues().getDisplayName());
            } else {
                params.add("信息维护系统管理员");
            }
            params.add(csSystemAdminEntity.getOrgName());
            params.add(userInfo.getValues().getUsername());
            params.add("nmgYjt@" + userInfo.getValues().getUsername().substring(7, 11));
            params.add(userInfo.getValues().getUsername());
            sendEntity.setType("admin.notification");
            sendEntity.setPhoneNumSet(phone);
            sendEntity.setTemplateParamSet(params);
            smsService.sendMS(sendEntity);
        }

        //设置默认权限
        String phoneC = bean.getCreatedBy();
        if (StrUtil.isNotEmpty(phoneC)){
            log.info("phoneC-systemAdmin:{}",JSONUtil.toJsonStr(csSystemAdminEntity));
            BusAuthUserAddDto busAuthUserAddDto = new BusAuthUserAddDto();
            busAuthUserAddDto.setPhone(bean.getPhone());
            busAuthUserAddDto.setUserName(bean.getName());
            busAuthUserAddDto.setAuthPhone(systemAdmin.getPhone());
            busAuthUserAddDto.setAuthUserName(systemAdmin.getName());
            busAuthUserAddDto.setAreaCode(area.getId());
            busAuthUserAddDto.setAreaName(area.getName());

            busAuthUserAddDto.setOrgId(csSystemAdminEntity.getOrgId());
            busAuthUserAddDto.setOrgName(csSystemAdminEntity.getOffice());


            busAuthUserAddDto.setDeptId(bean.getOrgId() );
            busAuthUserAddDto.setDeptName(bean.getOrgName());
            busAuthUserAddDto.setIp(bean.getIp());
            businessAuthService.defaultBuAuth(busAuthUserAddDto);
        }


        return csSystemAdminEntity.getId();
    }

    @Override
    public List<CsSystemAdmin> login(CsSystemAdminPwdBean bean) throws ParseException, JOSEException {

        List<CsSystemAdmin> admins = this.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getUsername()));

        String[] menus = {"1000000010", "1000000011", "1000000012", "1000000014", "1000000013"};
        String[] orgNames = {"救援队伍", "应急物资", "防护目标", "避难场所", "专家库", "专家"};
        List<String> menuList = Arrays.asList(menus);
        List<String> orgList = Arrays.asList(orgNames);
        if (!CollectionUtils.isEmpty(admins)) {
            //存在子部门,则为总管理员
            HashMap<String, String> headerParams = new HashMap<>();
            headerParams.put("Content-Type", "application/json");
            headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            HashMap<String, String> bodyParams = new HashMap<>();
            bodyParams.put("object_type", "DEPT");
            admins.forEach(ad -> {
//                List<CsBusiness>  businessList = csBusinessService.findByPone(ad.getPhone());
//                // 业务系统权限默认继承 ： 0:关闭 1:启用
//                ad.setInheritAuth(true);
//                if (CollUtil.isNotEmpty(businessList)) {
//                    for (CsBusiness csBusiness : businessList){
//                        if (StrUtil.isEmpty(csBusiness.getAuthCode())){
//                            ad.setInheritAuth(false);
//                        }
//                    }
//                }else {
//                    ad.setInheritAuth(false);
//                }
                ad.setInheritAuth(true);

                if (null != ad && menuList.contains(ad.getMenuId())) {

                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + ad.getOrgId() + "/children";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                    List<IDAASDeptResponse> listResponse =
                            JSONArray.parseArray(str3, IDAASDeptResponse.class);
                    String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + ad.getOrgId();
                    String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
                    IDAASDeptResponse deptResponse = JSONObject.parseObject(str4, IDAASDeptResponse.class);

                    CsSystemAdmin admin2 = this.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, ad.getCreatedBy()).eq(CsSystemAdmin::getOrgId, ad.
                            getOrgId()).orderByDesc(CsSystemAdmin::getId).last("limit 1"));
                    if (null != admin2 && menuList.contains(admin2.getMenuId())) {
                        ad.setPageType(3 + "");
                    } else {
                        if ((!CollectionUtils.isEmpty(listResponse) && orgList.contains(deptResponse.getValues().getName()))) {
                            //挂在父级节点的管理员,就是总管理员
                            if ("1000000013".equals(ad.getMenuId())) {
                                ad.setPageType(3 + "");
                            } else {
                                ad.setPageType(2 + "");
                            }

                        } else if (!CollectionUtils.isEmpty(listResponse) && null != deptResponse
                                && StringUtils.isNotEmpty(deptResponse.getId())
                                && !orgList.contains(deptResponse.getValues().getName())) {
                            ad.setPageType("3");
                        } else {
                            ad.setPageType("3");
                        }
                    }

                    if ("2".equals(ad.getPageType())) {
                        String url5 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getValues().getParentId();
                        String str5 = HttpUtils.httpGet(url5, bodyParams, headerParams);
                        IDAASDeptResponse parentDeptResponse = JSONObject.parseObject(str5, IDAASDeptResponse.class);
                        ad.setOrgName(parentDeptResponse.getValues().getName());
                    }


                }
                if (ad.getAdminType() == 2 || ad.getAdminType() == 7 || ad.getAdminType() == 8 ){
                    String menuPermission = ad.getMenuPermission();
                    if (StrUtil.isEmpty(menuPermission)){
                        ad.setMenuPermission(menuPermission + ":1000002024");
                    }
                }
            });
        }

        return admins;
    }

    @Override
    public String updateCsSystemAdmin(CsSystemAdminCreateBean bean, UserInfo loginAdminInfo) throws ParseException, JOSEException {

        CsSystemAdmin admin = this.getById(bean.getId());
        String id = null;

        if (StringUtils.isEmpty(bean.getMenuID()))
            bean.setMenuID(admin.getMenuId());
        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");
        String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children";
        String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
        List<IDAASDeptResponse> listResponse = JSONArray.parseArray(str3, IDAASDeptResponse.class);

        /**
         * 修改机构信息
         */
        String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId();
        String clientPostRes = HttpUtils.httpGet(url, bodyParams, headerParams);
        IDAASDeptResponse loginUserOrg = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);
        if (StringUtils.isNotEmpty(bean.getOrgName()) && (!bean.getOrgName().equals(loginUserOrg.getValues().getName()) || null != bean.getMaxUserNumber())) {
            Map<String, Object> map = new HashMap();
            map.put("name", bean.getOrgName());
            map.put("maxUserNumber", bean.getMaxUserNumber());
            Map updateBodyParams = new HashMap<>();
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId();
            updateBodyParams.put("values", map);
            String str1 = HttpUtils.sendHttpPut(url1, (JSONObject) JSON.toJSON(updateBodyParams), headerParams);
        }

        String[] menus = {"1000000001", "1000000002", "1000000003", "1000000004", "1000000005", "1000000006", "1000000008", "1000000010", "1000000011", "1000000012", "1000000013", "1000000014"};
        List<String> menuList = Arrays.asList(menus);

        if (CollectionUtils.isEmpty(listResponse)) {

            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId();
            String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
            IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str2, IDAASDeptResponse.class);
            if (null != idaasDeptResponse && "管理员".equals(idaasDeptResponse.getValues().getName())) {
                admin.setOrgId(idaasDeptResponse.getValues().getParentId());

                String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + idaasDeptResponse.getValues().getParentId() + "/children";
                String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);

                listResponse = JSONArray.parseArray(str4, IDAASDeptResponse.class);
                admin.setOrgId(idaasDeptResponse.getValues().getParentId());
            }
        }
        if (null != listResponse && !CollectionUtils.isEmpty(listResponse) && menuList.contains(admin.getMenuId())) {
            IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str3, "管理员");
            if (StringUtils.isEmpty(deptResponse.getId())) {
                CsSystemOrgCreateBean orgCreateBean = new CsSystemOrgCreateBean();
                orgCreateBean.setOrgName("管理员");
                orgCreateBean.setAreaCode(admin.getAreaCode());
                orgCreateBean.setMenuID(admin.getMenuId());
                IDAASOrgEntity orgEntity = createOrgToIDAAS(orgCreateBean, "管理员", admin.getOrgId());
                deptResponse = new IDAASDeptResponse();
                deptResponse.setId(orgEntity.getId());
            }
            //如果管理员账号挂在"管理员"节点,先逻辑删除用户,然后再创建新的用户
            CsSystemDeleteBean deleteBean = new CsSystemDeleteBean();
            Map bodyParam2 = new HashMap();
            bodyParam2.put("status", new ArrayList<>());

            List<String> orgIdList = new ArrayList<>();
            orgIdList.add(deptResponse.getId());
            bodyParam2.put("deptId", orgIdList);
            bodyParam2.put("identityClassification", "defaultIdentityClassification");

            if (!bean.getPhone().equals(admin.getPhone())) {
                Map bodyParams2 = new HashMap();
                bodyParams2.put("objectType", "USER");
                bodyParams2.put("values", bodyParam2);
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + deptResponse.getId() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams2), headerParams);
                IDAASUserResponse users = JSONObject.parseObject(str1, IDAASUserResponse.class);
                if (null != users && null != users.getTotal() && users.getTotal() > 0) {
                    users.getData().forEach(user -> {
                        try {
                            deleteBean.setId(user.getId());
                            userService.deleteCsSystemUser(deleteBean);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        } catch (JOSEException e) {
                            e.printStackTrace();
                        }
                    });

                }
            }

            UserInfo info = updateCsSystemUserToDefaultDept(bean, deptResponse.getId(), loginUserOrg.getValues().getRegionCode());
            boolean flag = false;
            if (null == info) {
                info = createUserToIDAAS(bean, deptResponse.getId(), StringUtils.substring(admin.getAreaCode(), 0, 9));
                flag = true;
            }
            if (null != info) {
                //删除旧的管理权限
                if (admin.getId().equals(bean.getId())) {
                    CsSystemAdmin systemAdmin = new CsSystemAdmin();
                    BeanUtils.copyProperties(bean, systemAdmin);
                    systemAdmin.setOrgId(admin.getOrgId());
                    if (StringUtils.isEmpty(systemAdmin.getAreaCode())) {
                        systemAdmin.setAreaCode(admin.getAreaCode());
                    }
                    systemAdmin.setMenuPermission(admin.getMenuPermission());
                    this.saveOrUpdate(systemAdmin);
                    if (!bean.getPhone().equals(admin.getPhone())) {
                        sendAdMsg(info, admin, flag);
                    }
                }
            }
            id = info.getId();
        } else {

            UserInfo info = updateCsSystemUserToDefaultDept(bean, admin.getOrgId(), loginUserOrg.getValues().getRegionCode());
            if (null != info) {
                //把原来管理员jiu
                List<CsSystemAdmin> admins = this.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getPhone()));
                if (!CollectionUtils.isEmpty(admins)) {
                    for (CsSystemAdmin ad : admins) {
                        if (!ad.getId().equals(admin.getId()))
                            this.removeById(ad.getId());
                    }
                }
                admin.setPhone(bean.getPhone());
                admin.setName(bean.getName());
                admin.setWorkUnit(bean.getWorkUnit());
                admin.setJob(bean.getJob());
                admin.setOrgName(bean.getOrgName());
                this.saveOrUpdate(admin);

                if (!bean.getPhone().equals(admin.getPhone())) {
                    sendAdMsg(info, admin, false);
                }
            }
            //更新资源信息

            String[] sourceMenus = {"1000000010", "1000000011", "1000000012", "1000000014"};
            List<String> sourceMenuList = Arrays.asList(sourceMenus);
            CsSystemSourceExt sourceExt1 = null;
            if (sourceMenuList.contains(bean.getMenuID())) {
                CsSystemSourceLevelBean sourceLevelBean = new CsSystemSourceLevelBean();
                sourceLevelBean.setCountry("");
                sourceExt1 = csSystemSourceExtService.getOne(
                        new LambdaQueryWrapper<CsSystemSourceExt>()
                                .eq(CsSystemSourceExt::getOrgId, admin.getOrgId())
                                .eq(CsSystemSourceExt::getMenuId, bean.getMenuID())
                                .orderByDesc(CsSystemSourceExt::getId).last("limit 1"));
                if (null == sourceExt1) {
                    sourceExt1 = new CsSystemSourceExt();
                    sourceExt1.setOrgId(admin.getOrgId());
                    sourceExt1.setSuperiorOrgId(admin.getSuperiorOrg());
                    sourceExt1.setMenuId(admin.getMenuId());
                    sourceExt1.setId(SnowflakeIdWorker.getUUID());
                }
                if (StringUtils.isNotEmpty(bean.getSourceType())) {
                    sourceExt1.setSourceType(bean.getSourceType());
                }
                if (!ObjectUtils.isEmpty(bean.getSourceLevel())) {
                    sourceExt1.setSourceLevel(JSON.toJSONString(bean.getSourceLevel()));
                }

                csSystemSourceExtService.saveOrUpdate(sourceExt1);
                idaasService.updateBaseSource(sourceExt1, bean);
            }
            id = info.getId();
        }
        if (!CollectionUtils.isEmpty(bean.getPreSetOrgInfos())) {

            String permission = ",";
            //预设成员单位权限
            for (CsSystemOrgPreSetBean preSetBean : bean.getPreSetOrgInfos()) {
                permission = permission + "," + preSetBean.getId();
                if (("1000000012".equals(preSetBean.getId()) || "1000000014".equals(preSetBean.getId())) && !CollectionUtils.isEmpty(preSetBean.getChildren())) {
                    CsSystemSourcePreSetInfo preSetInfo1 = preSetInfoService.getOne(
                            new LambdaQueryWrapper<CsSystemSourcePreSetInfo>()
                                    .eq(CsSystemSourcePreSetInfo::getOrgId, loginUserOrg.getId())
                                    .eq(CsSystemSourcePreSetInfo::getSourceId, preSetBean.getId())
                                    .orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
                    if (null != preSetInfo1) {
                        preSetInfo1.setPreSetTypes(JSONObject.toJSONString(preSetBean.getChildren()));
                        preSetInfo1.setUpdatedTime(new Date());
                        preSetInfo1.setUpdatedBy(bean.getCreatedBy());
                        preSetInfoService.updateById(preSetInfo1);
                    } else {
                        //存入预设防护目标类型
                        CsSystemSourcePreSetInfo preSetInfo = new CsSystemSourcePreSetInfo();
                        preSetInfo.setId(SnowflakeIdWorker.getUUID());
                        preSetInfo.setOrgId(loginUserOrg.getId());
                        preSetInfo.setSourceId(preSetBean.getId());
                        preSetInfo.setPreSetTypes(JSONObject.toJSONString(preSetBean.getChildren()));
                        preSetInfo.setCreatedBy(bean.getCreatedBy());
                        preSetInfo.setUpdatedBy(bean.getCreatedBy());
                        preSetInfo.setCreatedTime(new Date());
                        preSetInfo.setUpdatedTime(new Date());
                        preSetInfoService.save(preSetInfo);
                    }
                }

                if ("1000000007".equals(preSetBean.getId()) && null != preSetBean.getOrgChildren() && preSetBean.getOrgChildren().size() > 0) {
                    //获取子部门相关信息:/api/v1/departments/{department_id}/children
                    String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                    String interDeptId = null;
                    IDAASOrgEntity idaasOrg = null;
                    IDAASDeptResponse interDeptResponse = null;
                    CsSystemOrgCreateBean dept = new CsSystemOrgCreateBean();
                    BeanUtils.copyProperties(bean, dept);
                    dept.setUserId(bean.getCreatedBy());
                    dept.setAreaCode(loginUserOrg.getValues().getRegionCode());
                    dept.setAdminOrgID(admin.getOrgId());
                    if (!CollectionUtils.isEmpty(bean.getPreSetOrgInfos()) && JSONObject.toJSONString(bean.getPreSetOrgInfos()).contains("1000000007"))
                        dept.setPreSetOrgInfos(bean.getPreSetOrgInfos());
                    if (!StringUtils.isEmpty(bean.getPageType())) {
                        dept.setPageType(bean.getPageType());
                    }
                    dept.setCreatedBy(bean.getCreatedBy());
                    if (!str1.contains("内设机构")) {
                        idaasOrg = createOrgToIDAAS(dept, "内设机构", admin.getOrgId());
                        interDeptId = idaasOrg.getId();
                    } else {
                        /**
                         * 返回的子部门有内设机构就不用创建,直接获取相关内设机构信息,创建部门
                         */
                        interDeptResponse = getOrgInfoFromIDAASOrgList(str1, "内设机构");
                        interDeptId = interDeptResponse.getId();
                    }

                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptId + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    //IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                    if (!CollectionUtils.isEmpty(preSetBean.getOrgChildren())) {
                        for (CsSystemOrgItemPreSetBean office : preSetBean.getOrgChildren()) {
                            if (!str2.contains(office.getName())) {
                                dept.setMaxUserNumber(office.getMaxUserNumber());
                                createOrgToIDAAS(dept, office.getName(), interDeptId);
                            } else {
                                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, office.getName());
                                Map<String, Object> map = new HashMap();
                                map.put("name", office.getName());
                                map.put("maxUserNumber", office.getMaxUserNumber());
                                Map updateBodyParams = new HashMap<>();
                                String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId();
                                updateBodyParams.put("values", map);
                                String str4 = HttpUtils.sendHttpPut(url4, (JSONObject) JSON.toJSON(updateBodyParams), headerParams);
                            }
                        }
                    }
                }

                if ("1000002024".equals(preSetBean.getId())  && !CollectionUtils.isEmpty(preSetBean.getChildren()) ){
                    log.info("1000002024-update");
                    List<List<String>> listList1= preSetBean.getChildren();

                    List<CsBusinessUser> csBusinessUserList = new ArrayList<>();
//                    List<CsBusinessUserCode> userCodeList = new ArrayList<>();
                    List<CyBusAuthUserCodeDto> authUserDtos = new ArrayList<>();

                    for (List<String> l :  listList1){
                        CyBusAuthUserCodeDto cyBusAuthUserCodeDto = new CyBusAuthUserCodeDto();

                        CsBusinessUser csBusinessUser = new CsBusinessUser();

                        CsBusiness bu = csBusinessService.findByBusinessId(l.get(1));
                        csBusinessUser.setBusinessId(l.get(1));
                        csBusinessUser.setBusinessName(bu.getName());
                        cyBusAuthUserCodeDto.setBusinessId(l.get(1));

                        CsBusiness pBu = csBusinessService.findByBusinessId(l.get(0));
                        csBusinessUser.setParentBusinessId(l.get(0));
                        csBusinessUser.setParentBusinessName(pBu.getName());

                        csBusinessUser.setPhone(bean.getPhone());
                        csBusinessUser.setCreatedTime(new Date());
                        csBusinessUser.setCreatedBy(bean.getCreatedBy());
                        csBusinessUserList.add(csBusinessUser);
                        List<CsBusinessAuthCode>  authCodeList = csBusinessAuthCodeService.list(new LambdaQueryWrapper<CsBusinessAuthCode>()
                                .eq(CsBusinessAuthCode::getBusinessId, l.get(1))
                                .eq(CsBusinessAuthCode::getParentBusinessId, l.get(0)));

                       if (CollUtil.isNotEmpty(authCodeList) ){
                           for (CsBusinessAuthCode authCode : authCodeList ){
                               if ("管理员".equals(authCode.getAuthName())){
                                   cyBusAuthUserCodeDto.setAuthCode(authCode.getAuthCode());
                                   cyBusAuthUserCodeDto.setAuthName(authCode.getAuthName());
                                   authUserDtos.add(cyBusAuthUserCodeDto);
                               }
                           }

                       }

//                        for (CsBusinessAuthCode authCode : authCodeList){
//                            CsBusinessUserCode userCode = new CsBusinessUserCode();
//                            userCode.setAuthCode(authCode.getAuthCode());
//                            userCode.setAuthName(authCode.getAuthName());
//                            userCode.setPhone(bean.getPhone());
//                            userCode.setCreatedTime(new Date());
//                            userCode.setBusinessId(l.get(1));
//                            userCodeList.add(userCode);
//                        }

                    }
                    csBusinessUserService.remove(new LambdaQueryWrapper<CsBusinessUser>().eq(CsBusinessUser::getPhone, bean.getPhone()));
//                    csBusinessUserCodeService.remove(new LambdaQueryWrapper<CsBusinessUserCode>().eq(CsBusinessUserCode::getPhone, bean.getPhone()));

                    csBusinessUserService.saveBatch(csBusinessUserList);
//                    csBusinessUserCodeService.saveBatch(userCodeList);


                    CyBusAuthUserAddDto cyBusAuthUserAddDto = new CyBusAuthUserAddDto();
                    cyBusAuthUserAddDto.setPhone(bean.getPhone());
                    cyBusAuthUserAddDto.setUserName(bean.getName());
                    cyBusAuthUserAddDto.setAuthPhone(bean.getCreatedBy());
                    cyBusAuthUserAddDto.setAuthUserName(bean.getCreatedByName());
                    cyBusAuthUserAddDto.setAreaCode(bean.getAreaCode());
                    cyBusAuthUserAddDto.setAreaName(bean.getAreaName());
                    cyBusAuthUserAddDto.setDeptId(bean.getOrgId() );
                    cyBusAuthUserAddDto.setDeptName(bean.getOrgName());
                    cyBusAuthUserAddDto.setIp(bean.getIp());
                    cyBusAuthUserAddDto.setAuthUserDtos(authUserDtos);
                    //成员单位授权
                    businessAuthService.cydwsq(cyBusAuthUserAddDto);

                }

            }
            permission = permission + "::";
            if (permission.contains(",,")) {
                permission = permission.replace(",,", "");
            }
            admin.setMenuPermission(permission);
            this.updateById(admin);
        }

        return id;
    }


    public void sendAdMsg(UserInfo userInfo, CsSystemAdmin admin, boolean flag) throws
            ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

        UserInfo userResponse = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(userInfo.getValues().getUsername());

        if (flag) {
            Map restBean = new HashMap<>();
            restBean.put("password", "nmgYjt@" + userInfo.getValues().getUsername().substring(7, 11));
            restBean.put("scriptContent", "");
            restBean.put("script", false);
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/" + userInfo.getId() + "/reset_password";
            String resetStr = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(restBean), headerParams);
        }


        UserInfo userInfoFromIDAASByOpenId = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(admin.getCreatedBy());
        if (null != userResponse && StringUtils.isNotEmpty(userResponse.getValues().getUsername())) {
            YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
            List<String> params = new ArrayList<>();
            List<String> phone = new ArrayList<>();
            phone.add(userInfo.getValues().getUsername());
            params.add(userInfo.getValues().getDisplayName());
            params.add(userInfoFromIDAASByOpenId.getValues().getDisplayName());
            params.add(admin.getOrgName());
            params.add(userInfo.getValues().getUsername());
            if (flag) {
                params.add("nmgYjt@" + userInfo.getValues().getUsername().substring(7, 11));
            } else {
                params.add("@旧密码@");
            }
            params.add(userInfo.getValues().getUsername());
            sendEntity.setType("admin.notification");
            sendEntity.setPhoneNumSet(phone);
            sendEntity.setTemplateParamSet(params);
            smsService.sendMS(sendEntity);
        }
    }

    public UserInfo updateCsSystemUserToDefaultDept(CsSystemAdminCreateBean bean, String orgId, String areaCode) throws
            ParseException, JOSEException {

        UserInfo userInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getPhone());

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        if (null != userInfo) {
            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + userInfo.getValues().getDeptId();
            String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
            IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str2, IDAASDeptResponse.class);

            if (null != userInfo) {
                if (null != userInfo && "INACTIVE".equals(userInfo.getValues().getStatus())) {
                    headerParams.put("Content-Type", "application/json");
                    headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

                    String userPostRes2 =
                            HttpUtils.sendHttpPost("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/" + userInfo.getId() + "/enable", new JSONObject(), headerParams);
                }
                IDAASUserEntity po = new IDAASUserEntity();
                po.setDisplayName(bean.getName());
                po.setJobPosition(bean.getJob());
                po.setPrimaryMail(bean.getPhone() + "@qq.com");
                po.setOfficeAddress(bean.getOrgName());
                po.setUsername(bean.getPhone());
                po.setIsLeader(bean.getIsLeader());

                po.setToWX(1);
                po.setId(userInfo.getId());
                po.setJobLevel(bean.getJobLevel());
                po.setWorkUnit(bean.getWorkUnit());
                if (("管理员".equals(idaasDeptResponse.getValues().getName()) || "dpf-3f90f739227e498bb3505237e6c397bb".equals(idaasDeptResponse.getId()))) {
                    po.setDeptId(orgId);
                } else {
                    po.setDeptId(userInfo.getValues().getDeptId());
                }

                String[] menus = {"1000000010", "1000000011", "1000000012", "1000000013", "1000000014"};
                List<String> menuList = Arrays.asList(menus);
                Map map = new HashMap<>();
                map.put("values", po);
                String userPostRes = HttpUtils.sendHttpPut("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/users/" + userInfo.getId(), (JSONObject) JSON.toJSON(map), headerParams);
                log.info(userPostRes);

                if (StringUtils.isNotEmpty(userPostRes)) {
                    UserInfo user = JSONObject.parseObject(userPostRes, UserInfo.class);

                    if (null != user) {
                        CsSystemSourceExt sourceExt = new CsSystemSourceExt();
                        sourceExt.setSourceType(bean.getSourceType());
                        sourceExt.setRemark(bean.getDesc());
                        sourceExt.setSourceLevel(JSON.toJSONString(bean.getSourceLevel()));
                        sourceExt.setMenuId(bean.getMenuID());
                        CsSystemSourceExt one = csSystemSourceExtService.getOne(
                                new LambdaQueryWrapper<CsSystemSourceExt>()
                                        .eq(CsSystemSourceExt::getMenuId, bean.getMenuID())
                                        .eq(CsSystemSourceExt::getOrgId, orgId)
                                        .orderByDesc(CsSystemSourceExt::getId).last("limit 1"));
                        if (null != one) {
                            sourceExt.setId(one.getId());
                        }
                        if ("1000000013".equals(bean.getMenuID()) && one == null) {
                            sourceExt.setOrgId(user.getId());
                        } else {
                            sourceExt.setOrgId(orgId);
                        }
                        if (menuList.contains(bean.getMenuID())) {
                            if ("1000000010".equals(bean.getMenuID())) {
                                if (StringUtils.isNotEmpty(bean.getMajorDuties()))
                                    sourceExt.setMajorDuties(bean.getMajorDuties());
                                if (StringUtils.isNotEmpty(bean.getSecondaryDuties()))
                                    sourceExt.setSecondaryDuties(bean.getSecondaryDuties());
                            }
                            csSystemSourceExtService.saveOrUpdate(sourceExt);
                            //详情更新
                            idaasService.updateBaseSource(sourceExt, bean);
                        }

                    }
                    return user;
                }
            }
        } else {
            return createUserToIDAAS(bean, orgId, areaCode);
        }

        return null;
    }


    /**
     * 创建用户到 IDAAS
     *
     * @param bean
     * @param deptId
     * @param regionCode
     * @return
     * @throws ParseException
     * @throws JOSEException
     */
    UserInfo createUserToIDAAS(CsSystemAdminCreateBean bean, String deptId, String regionCode) throws
            ParseException, JOSEException {
        /**
         *第二步: 查询用户,如果存在就添加用户
         */
        IDAASUserEntity po = new IDAASUserEntity();
        po.setDisplayName(bean.getName());
        po.setJobPosition(bean.getJob());
        po.setPrimaryMail(bean.getPhone() + "@qq.com");
        po.setOfficeAddress(bean.getOrgName());
        po.setUsername(bean.getPhone());
        po.setDeptId(deptId);
        po.setIsLeader(bean.getIsLeader());
        po.setRegionCode(regionCode);
        po.setToWX(1);
        po.setJobTitle(bean.getJobLevel());
        po.setWorkUnit(bean.getWorkUnit());

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map map = new HashMap<>();
        map.put("values", po);
        map.put("objectType", "USER");
        String userPostRes = HttpUtils.sendHttpPost(
                "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects",
                (JSONObject) JSON.toJSON(map), headerParams);
        log.info(userPostRes);

        if (StringUtils.isNotEmpty(userPostRes)) {
            UserInfo user = JSONObject.parseObject(userPostRes, UserInfo.class);
            return user;
        }
        return null;
    }

    String setMenuPermission(String menuId) {

        switch (menuId) {
            case "1000000001":
                return "1000000001::";
            case "1000000002":
                return "1000000002::";
            case "1000000003":
                return "1000000001,1000000002,1000000006,1000000004::";
            case "1000000004":
                return "1000000001,1000000002,1000000006,1000000005::";
            case "1000000005":
                return "1000000015,1000000007,1000000016::";
            case "1000000006":
                //成员单位管理员根据成员单位的默认设置管理员
                return "1000000009,1000000007::";
            case "1000000007":
                return "1000000007::";
            case "1000000008":
                return "1000000009,1000000007::";
            case "1000000010":
                return "1000000010::";
            case "1000000011":
                return "1000000011::";
            case "1000000012":
                return "1000000012::";
            case "1000000013":
                return "1000000013::";
            case "1000000014":
                return "1000000014::";
            case "1000000015":
                return "1000000015::";
            case "1000000016":
                return "1000000016::";
            case "1000000017":
                return "1000000017::";
            default:
                return "";
        }
    }

    IDAASDeptResponse getOrgInfoFromIDAASOrgList(String clientPostRes, String orgName) {
        IDAASDeptResponse deptResponse = new IDAASDeptResponse();
        List<IDAASDeptResponse> listResponse =
                JSONArray.parseArray(clientPostRes, IDAASDeptResponse.class);
        if (!CollectionUtils.isEmpty(listResponse)) {
            for (IDAASDeptResponse dept : listResponse) {
                if (orgName.equals(dept.getValues().getName())) {
                    BeanUtils.copyProperties(dept, deptResponse);
                    if (StringUtils.isEmpty(deptResponse.getValues().getId())
                            || null == deptResponse.getValues().getId()) {
                        IDAASOrgEntity values = deptResponse.getValues();
                        values.setId(dept.getId());
                        values.setAncestor(dept.getValues().getAncestor());
                        deptResponse.setValues(values);
                    }
                    break;
                }
            }
        }
        return deptResponse;
    }

    IDAASOrgEntity createOrgToIDAAS(CsSystemOrgCreateBean dept, String orgName, String parentId) throws
            ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

        IDAASOrgEntity po = new IDAASOrgEntity();
        String areaCode = dept.getAreaCode().substring(0, 9);
        po.setOrgType("ob-1def915f1cb04dc190d48ea9cbf0f52c");
        po.setStatus("ENABLED");
        po.setRegionCode(areaCode);
        po.setParentId(parentId);
        po.setArea(idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, areaCode)).getId());
        if (StringUtils.isNotEmpty(orgName)) {
            po.setName(orgName);
        } else {
            if (!"1000000006".equals(dept.getMenuID()) && StringUtils.isNotEmpty(dept.getOffice())) {
                po.setName(dept.getOffice());
            } else {
                po.setName(dept.getOrgName());
            }
        }
        if (StringUtils.isNotEmpty(dept.getSourceType())) {
            CsSystemSourceType sourceType = sourceService.getById(dept.getSourceType());
            if (null != sourceType) {
                po.setSourceType(sourceType.getName());
            } else {
                po.setSourceType(dept.getSourceType());
            }
        }
        //创建部门的时候设置默认排序值,保证排序顺序
        if ("管理员".equals(po.getName())) {
            po.setUdOrder(999);
        } else if ("单位领导".equals(po.getName()) || "党委领导".equals(po.getName()) || "政府领导".equals(po.getName())) {
            po.setUdOrder(1);
        } else if ("内设机构".equals(po.getName()) || "党委总值班室".equals(po.getName()) || "政府总值班室".equals(po.getName())) {
            po.setUdOrder(3);
        } else if ("事业单位".equals(po.getName())) {
            po.setUdOrder(5);
        } else if ("救援队伍".equals(po.getName())) {
            po.setUdOrder(7);
        } else if ("专家".equals(po.getName())) {
            po.setUdOrder(9);
        } else if ("防护目标".equals(po.getName())) {
            po.setUdOrder(11);
        } else if ("避难场所".equals(po.getName())) {
            po.setUdOrder(13);
        } else {
            po.setUdOrder(20);
        }
        if ("1000000007".equals(dept.getMenuID())) {
            po.setMaxUserNumber(null == dept.getMaxUserNumber() ? 20 : dept.getMaxUserNumber());
        }
        po.setArea(idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, areaCode)).getId());

        Map map = new HashMap<>();
        map.put("values", po);
        String clientPostRes = HttpUtils.sendHttpPost(
                "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/",
                (JSONObject) JSON.toJSON(map), headerParams);

        IDAASDeptResponse org = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);
        po.setId(org.getId());
        String[] menus = {"1000000010", "1000000011", "1000000012", "1000000014"};
        String[] orgNames = {"救援队伍", "应急物资", "防护目标", "避难场所"};
        List<String> menuList = Arrays.asList(menus);
        List<String> orgLst = Arrays.asList(orgNames);

        if (null != dept.getMenuID() && menuList.contains(dept.getMenuID())) {
            Map<String, String> bodyParam = new HashMap();
            bodyParam.put("object_type", "DEPT");
            String parentOrgRes = HttpUtils.httpGet(
                    "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + org.getValues().getParentId(), bodyParam, headerParams);

            IDAASDeptResponse patentOrg = JSONObject.parseObject(parentOrgRes, IDAASDeptResponse.class);
            if (orgLst.contains(patentOrg.getValues().getName())) {

                CsSystemSourceExt sourceExt = new CsSystemSourceExt();
                sourceExt.setId(SnowflakeIdWorker.getUUID());
                sourceExt.setMenuId(dept.getMenuID());
                sourceExt.setRemark(dept.getDesc());
                sourceExt.setSourceType(dept.getSourceType());
                sourceExt.setOrgId(org.getId());
                sourceExt.setSourceLevel(JSONObject.toJSONString(dept.getSourceLevel()));

                Map<String, String> bodyParam2 = new HashMap();
                bodyParam2.put("object_type", "DEPT");
                String parentOrgRes2 = HttpUtils.httpGet(
                        "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + patentOrg.getValues().getParentId(),
                        bodyParam2, headerParams);
                IDAASDeptResponse patentOrg2 = JSONObject.parseObject(parentOrgRes2, IDAASDeptResponse.class);
                if (null != patentOrg2 && null != patentOrg2.getValues()) {
                    sourceExt.setSuperiorOrgId(patentOrg2.getId());
                    sourceExt.setSuperiorOrgName(patentOrg2.getValues().getName());
                }
                csSystemSourceExtService.save(sourceExt);
                //保存基础资源
                idaasService.saveBaseSource(sourceExt, dept);
            }
        }
        return po;
    }
}
